package com.libre.security;

import com.libre.common.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

//2.身份验证
@Slf4j
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private SecurityUserService userService;

    /**
     * 自定义验证方式
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        log.info(">>>>>>>>> 用户：{}进入授权方法 >>>>>>>>>", username);
        String password = (String) authentication.getCredentials();
        SecurityUser user = (SecurityUser) userService.loadUserByUsername(username);
        if (user == null) {
            throw new BadCredentialsException("用户名不存在");
        }
        // 校验用户密码
        //密码加密规则：数据库密码(password)+盐(salt),进行MD5加密
        if (!user.getPassword().equals(MD5Util.MD5(password + user.getSalt()))) {
            throw new BadCredentialsException("登录密码不正确");
        }
        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }

}